package com.hspedu.newData.力扣周赛.周赛.第448;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-04 
 * @Version: 1.0
 */

// todo
public class LC100626填充特殊网络 {

    public static int[][] specialGrid(int N) {
        // 计算网格的大小 2^N x 2^N
        int size = (int) Math.pow(2, N);

        // 如果 N = 0 时，直接返回 1x1 的网格
        if (size == 1) {
            int[][] grid = new int[1][1];
            grid[0][0] = 0;  // 只有一个元素，填充为 0
            return grid;
        }

        // 否则，创建网格并开始填充
        int[][] grid = new int[size][size];
        fillGrid(grid, 0, 0, size, 0, (int) Math.pow(2, 2 * N) - 1);
        return grid;
    }

    // 递归填充网格
    public static void fillGrid(int[][] grid, int rowStart, int colStart, int size, int startValue, int endValue) {
        if (size == 1) {
            grid[rowStart][colStart] = startValue;
            return;
        }

        int mid = size / 2;
        int range = endValue - startValue + 1;

        // 填充四个象限

        fillGrid(grid, rowStart, colStart + mid, mid, startValue, startValue + range / 4 - 1);  // 右上
        fillGrid(grid, rowStart + mid, colStart + mid, mid, startValue + range / 4, startValue + range / 2 - 1);  // 右下
        fillGrid(grid, rowStart + mid, colStart, mid, startValue + range / 2, startValue + 3 * range / 4 - 1);  // 左下
        fillGrid(grid, rowStart, colStart, mid, startValue + 3 * range / 4, endValue);  // 左上
    }

    // 打印网格
    public static void printGrid(int[][] grid) {
        for (int[] row : grid) {
            for (int val : row) {
                System.out.print(val + "\t");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int N = 3; // 可修改 N 的值
        int[][] grid = specialGrid(N);
        printGrid(grid);
    }
}
